package com.bianqian.demo.controller;

import com.bianqian.demo.dto.*;
import com.bianqian.demo.entity.User;
import com.bianqian.demo.service.UserService;
import com.bianqian.demo.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/pages")
@RequiredArgsConstructor
@Slf4j
@Validated
public class AuthController {
    
    private final UserService userService;
    private final JwtUtil jwtUtil;
    
    /**
     * 用户登录
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @PostMapping("/login")
    public ApiResponse<AuthResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            log.info("用户登录请求，账号：{}", loginRequest.getAccount());
            
            // 验证用户登录
            User user = userService.login(loginRequest.getAccount(), loginRequest.getPassword());
            
            // 生成JWT token
            String token = jwtUtil.generateToken(user.getId(), user.getAccount());
            
            // 构建用户信息
            UserInfo userInfo = new UserInfo(
                user.getId(),
                user.getAccount(),
                user.getNickname(),
                user.getAvatar()
            );
            
            // 构建响应
            AuthResponse authResponse = new AuthResponse(token, userInfo);
            
            log.info("用户登录成功，ID：{}", user.getId());
            return ApiResponse.success("登录成功", authResponse);
            
        } catch (RuntimeException e) {
            log.error("用户登录失败：{}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("用户登录异常：", e);
            return ApiResponse.error("登录失败，请重试");
        }
    }
    
    /**
     * 用户注册
     * @param registerRequest 注册请求
     * @return 注册响应
     */
    @PostMapping("/register")
    public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            log.info("用户注册请求，账号：{}", registerRequest.getAccount());
            
            // 注册用户
            User user = userService.register(
                registerRequest.getNickname(),
                registerRequest.getAccount(),
                registerRequest.getPassword()
            );
            
            // 生成JWT token
            String token = jwtUtil.generateToken(user.getId(), user.getAccount());
            
            // 构建用户信息
            UserInfo userInfo = new UserInfo(
                user.getId(),
                user.getAccount(),
                user.getNickname(),
                user.getAvatar()
            );
            
            // 构建响应
            AuthResponse authResponse = new AuthResponse(token, userInfo);
            
            log.info("用户注册成功，ID：{}", user.getId());
            return ApiResponse.success("注册成功", authResponse);
            
        } catch (RuntimeException e) {
            log.error("用户注册失败：{}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("用户注册异常：", e);
            return ApiResponse.error("注册失败，请重试");
        }
    }
    
    /**
     * 用户登出
     * @return 登出响应
     */
    @PostMapping("/logout")
    public ApiResponse<Object> logout() {
        try {
            log.info("用户登出请求");
            
            // 登出逻辑（实际项目中可能需要将token加入黑名单）
            log.info("用户登出成功");
            return ApiResponse.success("登出成功", null);
            
        } catch (Exception e) {
            log.error("用户登出异常：", e);
            return ApiResponse.error("登出失败，请重试");
        }
    }
}

